#include "../include/head.h"

// 写入商品信息到文件
void write_file(Pnode_list head)
{
    FILE *fp = fopen("./goods_management/data/goods.txt", "wb");
    if (fp == NULL)
    {
        printf("文件打开失败\n");
        return;
    }

    Pnode_list p = head->next; // 头节点不存数据
    while (p != head)
    {
        fwrite(&p->info, sizeof(Data_type), 1, fp);
        p = p->next;
    }
    fclose(fp);
}

// 从文件读取商品信息
void read_file(Pnode_list head)
{
    FILE *fp = fopen("./goods_management/data/goods.txt", "rb");
    if (fp == NULL)
    {
        printf("打开文件失败\n");
        return;
    }

    Data_type data; // 用来读结点的数据
    while (fread(&data, sizeof(Data_type), 1, fp) == 1)
    {
        tail_insert(head, data);
    }
    remove_duplicates(head);
    fclose(fp);
}
// 输出商品信息
void outputdata(Pnode_list head)
{
    Pnode_list p = head->next;
    bubble_sort_by_id(head);
    printf("商品编号\t商品名称\t商品价格\t商品数量\n");
    while (p != head)
    {
        printf("%d\t\t%s\t\t%.2f\t\t%d\n", p->info.id, p->info.name, p->info.price, p->info.stock);
        p = p->next;
    }
}
// 输入商品信息
void inputdata(Pnode_list head)
{
    Data_type goods;
    printf("------------------------商品入库页面--------------------------\n");
    // 输入商品信息
    printf("请输入商品信息（编号 名称 价格 库存）:");
    scanf("%d %19s %f %d", &goods.id, goods.name, &goods.price, &goods.stock);
    getchar(); // 清除输入缓冲区

    // 检查ID是否已存在
    if (id_list_get(head, goods.id) != NULL)
    {
        printf("错误：商品ID %d 已存在\n", goods.id);
    }
    else if (string_list_get(head, goods.name) != NULL)
    {
        printf("错误：商品名称%s 已存在\n", goods.name);
    }
    else
    {
        // 插入链表并保存到文件
        tail_insert(head, goods);
        write_file(head);
        printf("商品添加成功\n");
    }
    outputdata(head);
    printf("按回车键继续\n");
    scanf("%*c");
}

